/*
 * @Author: wangdazhuang
 * @Date: 2024-08-19 11:55:58
 * @LastEditTime: 2025-02-20 20:36:20
 * @LastEditors: wangdazhuang
 * @Description: 
 * @FilePath: /pornhub_app/lib/views/player/video_play_page.dart
 */
import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:pornhub_app/assets/styles.dart';
import 'package:pornhub_app/components/easy_button.dart';
import 'package:pornhub_app/components/grid_view/heighted_grid_view.dart';
import 'package:pornhub_app/components/image_view.dart';
import 'package:pornhub_app/generate/app_image_path.dart';
import 'package:pornhub_app/model/video_base_model.dart';
import 'package:pornhub_app/routes/routes.dart';
import 'package:pornhub_app/utils/ad_jump.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/extension.dart';
import 'package:pornhub_app/utils/utils.dart';
import 'package:pornhub_app/views/player/controllers/video_play_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/views/player/views/download_ad.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'views/av_player_loading.dart';
import 'views/common_ad.dart';
import 'views/media_kit_custom_controls.dart' as custom;
import 'views/stop_ad.dart';

class VideoPlayPage extends StatelessWidget {
  const VideoPlayPage({super.key});

  _buildPlayer(VideoPlayController _, BuildContext context) {
    final unInitialized = !_.playerInitialized || _.player == null;
    if (unInitialized) return const AvPlayerLoading();
    final videoH = VideoPlayController.videoH;
    final themColor = COLOR.hexColor("#ff960f");

    final controls = MaterialVideoControlsTheme(
      normal: MaterialVideoControlsThemeData(
        seekBarPositionColor: themColor,
        seekBarThumbColor: themColor,
      ),
      fullscreen: MaterialVideoControlsThemeData(
        seekBarPositionColor: themColor,
        seekBarThumbColor: themColor,
      ),
      child: custom.MediaKitCustomControls(
        buildContext: context,
        viewSize: Size(Get.width, videoH),
        texturePos: Rect.fromLTWH(0, 0, Get.width, videoH),
      ),
    );
    final videoAsp = _.videoAsp();
    if (kIsWeb) {
      return Video(
        key: Key('${_.currentVideo.videoId ?? 0}'),
        controller: _.playerVC!,
        aspectRatio: videoAsp,
        filterQuality: FilterQuality.none,
        controls: (__) => controls,
        onEnterFullscreen: () async {
          _webAutoPlayAction(_, context);
        },
        onExitFullscreen: () async {
          _webAutoPlayAction(_, context);
        },
      );
    }
    return SizedBox(
      width: Get.width,
      height: VideoPlayController.videoH,
      child: Video(
        key: Key('${_.currentVideo.videoId ?? 0}'),
        filterQuality: FilterQuality.none,
        controller: _.playerVC!,
        aspectRatio: videoAsp,
        controls: (__) => controls,
      ),
    );
  }

  void btnFunction(bool isVip, [VideoPlayController? _]) {
    if (isVip) {
      if (_ != null) {
        Get.toNamed(Routes.vip);
      } else {
        Get.toShare();
      }
    } else {
      if (_ != null) {
        _.buyAction();
      } else {
        Get.toNamed(Routes.vip);
      }
    }
  }

  _buildBtns(VideoPlayController _) {
    var isVipVideo = _.currentVideo.videoType == 1;
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 7.w),
          decoration: BoxDecoration(
              color: COLOR.hexColor('#FEE041'),
              borderRadius: BorderRadius.circular(18.w)),
          child: Text(
            isVipVideo ? '邀请好友' : '上传视频',
            style: TextStyle(color: COLOR.hexColor('#0C0935'), fontSize: 16.w),
          ),
        ).onTap(() {
          btnFunction(isVipVideo);
        }),
        SizedBox(
          width: 20.w,
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 7.w),
          decoration: BoxDecoration(
              color: COLOR.hexColor('#B93FFF'),
              borderRadius: BorderRadius.circular(18.w)),
          child: Text(
            isVipVideo ? '开通会员' : '${_.currentVideo.price}金币购买',
            style: TextStyle(color: COLOR.hexColor('#fff'), fontSize: 16.w),
          ),
        ).onTap(() {
          btnFunction(isVipVideo, _);
        })
      ],
    );
  }

  _buildPermission(VideoPlayController _) {
    if (_.showTip) {
      var isVipVideo = _.currentVideo.videoType == 1;
      var title = '试看结束';
      var tip = isVipVideo ? '开通会员观看完整版，邀请好友得会员' : '该视频为用户上传的金币视频，购买后永久观看';
      return Positioned.fill(
          child: Stack(
        children: [
          Container(
            color: const Color.fromRGBO(0, 0, 0, 0.5),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  title,
                  style: TextStyle(fontSize: 16.w, color: Colors.white),
                ),
                SizedBox(
                  height: 8.w,
                ),
                Text(
                  tip,
                  style: TextStyle(
                    fontSize: 16.w,
                    color: Colors.white,
                  ),
                ).marginBottom(23.w),
                _buildBtns(_)
              ],
            ),
          ),
          Positioned(
              top: 24,
              left: 12,
              child: const Icon(
                Icons.arrow_back_ios,
                size: 25,
                color: COLOR.white,
              ).onTap(() {
                Get.back();
              }))
        ],
      ));
    }
    return const SizedBox.shrink();
  }

  Widget _buildPlayAdMark(VideoPlayController _) {
    final hasAd = _.playerInitialized &&
        _.markAd != null &&
        _.markAd!.adImage != null &&
        _.markAd!.adImage!.isNotEmpty &&
        _.showMarkAd &&
        _.adTimerCount > 0;
    final size = Size(30.w, 30.w);
    final adSize = Size(160.w, 32.w);
    return Visibility(
      visible: hasAd,
      child: Positioned(
        left: 12.w,
        bottom: kIsWeb ? 10.w : 35.w,
        width: adSize.width + size.height / 2,
        height: adSize.height + size.height / 2,
        child: (_.markAd != null &&
                _.markAd!.adImage != null &&
                _.markAd!.adImage!.isNotEmpty)
            ? Stack(
                children: [
                  Positioned(
                    bottom: 0,
                    left: 0,
                    child: ImageView(
                      src: _.markAd!.adImage ?? '',
                      fit: BoxFit.fill,
                      width: adSize.width,
                      height: adSize.height,
                    ),
                  ),
                  Positioned(
                    right: 0,
                    top: 0,
                    child: Container(
                      width: size.width,
                      height: size.height,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: const Color.fromRGBO(0, 0, 0, 0.6),
                          borderRadius:
                              BorderRadius.circular(size.height / 2.0)),
                      child: Text(
                        '${_.adTimerCount}',
                        style: kTextStyle(Colors.white, fontsize: 12.w),
                      ),
                    ),
                  ),
                ],
              ).onTap(() {
                kAdjump(_.markAd, _.markAd!.adId);
              })
            : const SizedBox.shrink(),
      ),
    );
  }

  void _visibleAction(VisibilityInfo info) {
    final _ = Get.find<VideoPlayController>();
    if (info.visibleFraction == 1) {
    } else {
      /// push了或者销毁了
      final isLive = Get.isRegistered<VideoPlayController>() ||
          Get.isPrepared<VideoPlayController>();
      if (isLive) {
        ///暂停
        _.player?.pause();
      }
    }
  }

  ///顶部播放器
  _buildPlayerView(VideoPlayController _, BuildContext context) {
    return SizedBox(
      height: VideoPlayController.videoH,
      width: double.infinity,
      child: Stack(
        children: [
          _buildPlayer(_, context),
          _buildPermission(_),
          _buildPlayAdMark(_),
          StopAd(vc: _),
        ],
      ),
    );
  }

  ///2个按钮
  Widget _buildBottomBtns(VideoPlayController _) {
    return Row(
      children: [
        Expanded(
            child: EasyButton.child(
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset(
                _.currentVideo.like == true
                    ? AppImagePath.player_like_y
                    : AppImagePath.player_like,
                width: 18.w,
                height: 18.w,
              ),
              5.w.horizontalSpace,
              Text(
                Utils.numFmtCh(_.currentVideo.fakeLikes ?? 0),
                style: kTextStyle(Colors.white.withValues(alpha: 0.8),
                    fontsize: 12.w),
              )
            ],
          ),
          backgroundColor: const Color.fromRGBO(255, 255, 255, 0.2),
          height: 44.w,
          borderRadius: BorderRadius.circular(22.w),
          borderColor: const Color.fromRGBO(255, 255, 255, 0.23),
          borderWidth: 1.w,
          onTap: () {
            _.likeAction();
          },
        )),
        15.w.horizontalSpace,
        Expanded(
            child: EasyButton.child(
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset(
                AppImagePath.player_share,
                width: 18.w,
                height: 18.w,
              ),
              5.w.horizontalSpace,
              Text(
                '分享',
                style: kTextStyle(Colors.white.withValues(alpha: 0.8),
                    fontsize: 12.w),
              )
            ],
          ),
          backgroundColor: const Color.fromRGBO(255, 255, 255, 0.2),
          height: 44.w,
          borderRadius: BorderRadius.circular(22.w),
          borderColor: const Color.fromRGBO(255, 255, 255, 0.23),
          borderWidth: 1.w,
          onTap: () {
            Get.toShare();
          },
        )),
      ],
    );
  }

  _buildGuessLikeCell(VideoBaseModel model, VideoPlayController _) {
    return Column(
      children: [
        Container(
          width: (1.sw - 32.w) / 2.0,
          height: 92.w,
          clipBehavior: Clip.hardEdge,
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(8.w)),
          child: ImageView(src: model.hCover),
        ),
        5.w.verticalSpace,
        SizedBox(
          width: (1.sw - 32.w) / 2.0,
          child: Text(
            model.title ?? '',
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
            style: kTextStyle(Colors.white, fontsize: 13.w),
          ),
        )
      ],
    ).onTap(() {
      _.getVideoById(model.videoId ?? 0);
    });
  }

  ///底部所有东西
  _buildBottom(VideoPlayController _) {
    return Expanded(
      child: SizedBox(
        width: double.infinity,
        child: CustomScrollView(
          slivers: [
            5.w.verticalSpace.sliverBox,

            ///下载体验广告
            const DownloadAd().sliverBox,
            10.w.verticalSpace.sliverBox,

            ///标题
            Text(
              _.currentVideo.title ?? '',
              style: kTextStyle(Colors.white,
                  fontsize: 15.w, weight: FontWeight.w500),
            ).sliverBox,
            10.w.verticalSpace.sliverBox,

            ///播放次数
            Text(
              '${Utils.numFmtCh(_.currentVideo.fakeWatchNum ?? 0)}次播放',
              style: kTextStyle(Colors.white.withValues(alpha: 0.6),
                  fontsize: 12.w),
            ).sliverBox,
            10.w.verticalSpace.sliverBox,
            _buildBottomBtns(_).sliverBox,
            12.w.verticalSpace.sliverBox,
            const CommonAd().sliverBox,
            15.w.verticalSpace.sliverBox,
            Text(
              '站长推荐',
              style: kTextStyle(Colors.white,
                  fontsize: 16.w, weight: FontWeight.w600),
            ).sliverBox,
            10.w.verticalSpace.sliverBox,

            HeightedGridView.sliver(
              crossAxisCount: 2,
              itemCount: _.guessLikeItems.length,
              itemBuilder: (ctx, i) {
                final model = _.guessLikeItems[i];
                return _buildGuessLikeCell(model, _);
              },
              rowMainAxisAlignment: MainAxisAlignment.start,
              columnSpacing: 8.w,
              rowSepratorBuilder: (context, index) => SizedBox(height: 8.w),
              noData: false,
            ),
          ],
        ).paddingHorizontal(12.w),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final _ = Get.find<VideoPlayController>();
    return VisibilityDetector(
      key: const Key('video-player'),
      onVisibilityChanged: _visibleAction,
      child: SafeArea(
        child: Scaffold(
          backgroundColor: Colors.black,
          body: GetBuilder<VideoPlayController>(
            init: _,
            autoRemove: false,
            builder: (__) {
              if (_.currentVideo.videoId == 0) return const AvPlayerLoading();
              return Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  _buildPlayerView(_, context),
                  _buildBottom(_),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  ///web下全屏后自动播放
  void _webAutoPlayAction(VideoPlayController _, BuildContext context) {
    Timer.periodic(
      const Duration(milliseconds: 1000),
      (timer) {
        _.player?.play();
        timer.cancel();
      },
    );
  }
}
